<template>
  <div class="container">
    <!-- 获取当前地址  -->
    <el-dialog
      title="打卡地点"
      :visible.sync="isShowDialog"
      :close-on-click-modal="false"
      @close="handleClose"
      custom-class="dialog-minwidth"
      :modal-append-to-body="false"
    >
      <el-form
        :model="addressFormData"
        label-width="80px"
        ref="addressFormData1"
        :rules="addressFormRules"
      >
        <!-- <el-row class="row-padding-bottom">
          <el-col :span="24" class="col-position">可在地图中通过移动标记点进行更精确定位</el-col>
        </el-row> -->
        <div class="reminder">
          <i class="el-icon-warning"></i>
          <span>可在地图中通过移动标记点进行更精确定位</span>
        </div>
        <div style="padding: 0 20px">
          <el-row class="row-padding-bottom">
            <el-col :span="24" class="col-position">
              <div id="l-map" style="height: 300px">地图</div>
            </el-col>
          </el-row>
          <el-row class="row-padding-bottom">
            <el-col :span="18">
              <el-form-item label="打卡地址" prop="address">
                <el-input
                  v-model="addressFormData.address"
                  class="mWidth"
                  id="suggestId"
                ></el-input>
                <div
                  id="searchResultPanel"
                  style="
                    border: 1px solid #c0c0c0;
                    width: 150px;
                    height: auto;
                    display: none;
                  "
                ></div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="row-padding-bottom">
            <el-col :span="24">
              <el-form-item label="打卡范围" prop="range">
                <el-select
                  v-model="addressFormData.range"
                  filterable
                  placeholder="请选择"
                  class="sWidth"
                >
                  <el-option
                    v-for="item in rangeList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option> </el-select
                >&nbsp;&nbsp;&nbsp;&nbsp;员工可在范围内正常打卡
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="handleClose" v-sdc class="cancel"
          >取消</el-button
        >
        <el-button type="primary" @click.native="editSubmit" v-sdc class="save"
          >确认</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  props: {
    addressFormData: {
      type: Object,
    },
    type: {
      type: String,
    },
    isJZ: {
      type: Boolean,
    },
  },
  data() {
    var checkLat = (rule, value, callback) => {
      var that = this
      var address = ''
      if (that.addressFormData.address) {
        var address = that.addressFormData.address.replace(/\s/g, '')
      }

      setTimeout(function () {
        if (
          !that.addressFormData.lat ||
          !address ||
          (that.flag == false && !that.addressFormData.lat)
        ) {
          that.flag = true
          return callback(new Error('请输入有效地址'))
        } else {
          callback()
        }
      }, 1000)
    }
    var checDepartment = (rule, value, callback) => {
      this.$nextTick(function () {
        if ($('#choiceNameBox').find('li').length < 1) {
          return callback(new Error('请选择打卡人员'))
        } else {
          callback()
        }
      })
    }
    return {
      // 弹窗验证
      addressFormRules: {
        address: [
          {
            required: true,
            validator: checkLat,
            trigger: 'blur',
          },
        ],
        range: [
          {
            required: true,
            pattern: /^[\s\S]*.*[^\s][\s\S]*$/,
            message: '请输入打卡范围',
            trigger: 'change',
          },
        ],
      },
      LocationPoint: '', //所在地址
      rangeList: [
        {
          value: 50,
          label: '50米',
        },
        {
          value: 100,
          label: '100米',
        },
        {
          value: 200,
          label: '200米',
        },
        {
          value: 300,
          label: '300米',
        },
        {
          value: 500,
          label: '500米',
        },
      ],
      //编辑，之前的打卡点id
      id: '',
      flag: true,
      isShowDialog: true,
    }
  },

  computed: {},
  created() {
    if (this.isJZ) {
      this.rangeList.push(
        {
          value: 1000,
          label: '1000米',
        },
        {
          value: 2000,
          label: '2000米',
        },
        {
          value: 3000,
          label: '3000米',
        },
        {
          value: 5000,
          label: '5000米',
        }
      )
    }
  },
  mounted() {
    this.$nextTick(function () {
      this.getLocation()
    })
  },
  methods: {
    getLocation() {
      var that = this
      var map = new BMap.Map('l-map')

      function myFun(result) {
        var cityName = result.name
        map.setCenter(cityName)
        that.LocationPoint = cityName
        that.initMap(that.type)
      }
      var myCity = new BMap.LocalCity()
      myCity.get(myFun)
    },
    initMap(type) {
      var that = this
      //是否隐藏下拉框标识
      var isHide = true

      function G(id) {
        return document.getElementById(id)
      }

      var map = new BMap.Map('l-map')

      // 编辑，将之前的经纬度设置为地图中心点

      if (type == 'edit') {
        var point = new BMap.Point(
          that.addressFormData.lon,
          that.addressFormData.lat
        )

        if (type == 'edit') {
          setTimeout(function () {
            $('#suggestId').val(that.addressFormData.address)
            isHide = false
          }, 100)
        }

        openDragend(point)
      } else {
        // 添加,将当前ip获取到的区域设置为地图中心点
        var myGeo = new BMap.Geocoder()
        // 将地址解析结果显示在地图上,并调整地图视野
        myGeo.getPoint(
          that.LocationPoint,
          function (point) {
            if (point) {
              openDragend(point)
            } else {
              // alert("您选择地址没有解析到结果!");
            }
          },
          '北京市'
        )
      }

      function openDragend(point) {
        map.centerAndZoom(point, 16)

        var mk = new BMap.Marker(point)

        map.addOverlay(mk)
        map.panTo(point)

        // 初始化可拖拽
        mk.enableDragging()
        mk.addEventListener('dragend', function (e) {
          that.addressFormData.lon = e.point.lng
          that.addressFormData.lat = e.point.lat
          var myGeo = new BMap.Geocoder()
          // 根据坐标得到地址描述
          myGeo.getLocation(
            new BMap.Point(e.point.lng, e.point.lat),
            function (result) {
              if (result) {
                that.addressFormData.address = result.address
                $('#suggestId').val(result.address)
                isHide = false
              }
            }
          )
        })
      }

      //增加滚轮放大缩小
      map.enableScrollWheelZoom(true)

      var ac = new BMap.Autocomplete({
        input: 'suggestId',
        location: map,
        onSearchComplete: function (data) {
          if (!isHide) {
            ac.hide()
            isHide = true
          }
        },
      }) //建立一个自动完成的对象

      ac.addEventListener('onhighlight', function (e) {
        //鼠标放在下拉列表上的事件
        var str = ''
        var _value = e.fromitem.value
        var value = ''
        if (e.fromitem.index > -1) {
          value =
            _value.province +
            _value.city +
            _value.district +
            _value.street +
            _value.business
        }
        str =
          'FromItem<br />index = ' + e.fromitem.index + '<br />value = ' + value

        value = ''
        if (e.toitem.index > -1) {
          _value = e.toitem.value
          value =
            _value.province +
            _value.city +
            _value.district +
            _value.street +
            _value.business
        }
        str +=
          '<br />ToItem<br />index = ' +
          e.toitem.index +
          '<br />value = ' +
          value
        G('searchResultPanel').innerHTML = str
      })

      var myValue
      ac.addEventListener('onconfirm', function (e) {
        var suggestVal = $('#suggestId').val()
        $('#suggestId').bind('input propertychange', function () {
          if (that.addressFormData.address != suggestVal) {
            that.flag = false
            that.addressFormData.lon = ''
            that.addressFormData.lat = ''
          }
        })
        //鼠标点击下拉列表后的事件
        var _value = e.item.value

        myValue =
          _value.province +
          _value.city +
          _value.district +
          _value.street +
          _value.business
        G('searchResultPanel').innerHTML =
          'onconfirm<br />index = ' +
          e.item.index +
          '<br />myValue = ' +
          myValue
        setPlace()
      })

      function setPlace() {
        map.clearOverlays() //清除地图上所有覆盖物
        function myFun() {
          var pp = local.getResults().getPoi(0).point //获取第一个智能搜索的结果
          that.addressFormData.lon = pp.lng
          that.addressFormData.lat = pp.lat
          openDragend(pp)
        }
        var local = new BMap.LocalSearch(map, {
          //智能搜索
          onSearchComplete: myFun,
        })

        local.search(myValue)
      }
    },
    handleClose() {
      // this.$emit('handleClose',this.addressFormData);
      this.$emit('editSubmit', this.addressFormData)
    },
    editSubmit(e) {
      this.$refs.addressFormData1.validate((valid) => {
        if (valid) {
          this.addressFormData.address = $('#suggestId').val()
          this.$emit('editSubmit', this.addressFormData)
        } else {
        }
      })
    },
  },
}
</script>

<style scoped lang="less">
#l-map {
  margin: 24px 0;
}

@media screen and (max-width: 1280px) {
  #l-map {
    height: 200px !important;
  }
}

@media all and (min-width: 1360px) and (max-width: 1470px) {
  #l-map {
    height: 235px !important;
  }
}
/deep/.el-dialog__body {
  padding: 0 !important;
}
.reminder {
  color: #666;
  font-size: 14px;
  background: #fffbe6;
  line-height: 36px;
  border-radius: 3px;
  padding: 0 20px;
  i {
    color: #ffaa00;
    margin-right: 4px;
    font-size: 20px;
    vertical-align: -2px;
  }
  span {
    color: #ff4d4a;
  }
}
</style>
